package com.example.wx.demo.wx;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import weixin.popular.api.SnsAPI;
import weixin.popular.api.UserAPI;
import weixin.popular.util.JsUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zhangd
 */
@Slf4j
@Service
public class AccountServiceImpl implements AccountService {


    /**
     * 微信appid
     */
    @Value("${wx.appid}")
    private String appId;

    /**
     * 微信秘钥
     */
    @Value("${wx.appsecret}")
    private String appSecret;


    @Override
    public String getAccountTokenWeixin(String openId) {
        return TokenSingleton.getTokenSingleton().getWeixinToken();
    }


    @Override
    public String getOpenId(String code) {
        try {
            return SnsAPI.oauth2AccessToken(appId, appSecret, code).getOpenid();
        } catch (Exception e) {
            throw new RuntimeException("GET_OPENID_FAIL");
        }
    }


    @Override
    public boolean checkIsFollow(String openid) {
        try {
            return 1 == UserAPI.userInfo(TokenSingleton.getTokenSingleton().getWeixinToken(), openid).getSubscribe();
        } catch (Exception e) {
            throw new RuntimeException("INVALID_OPENID");
        }
    }

    @Override
    public String getJSSign(String url) {
        String nonceStr = UUID.randomUUID().toString();
        String jsApiTicket = TokenSingleton.getTokenSingleton().getJsApiTicket();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String signature = JsUtil.generateConfigSignature(nonceStr, jsApiTicket, timestamp, url);
        Map<String, String> map = new HashMap<>(16);
        map.put("signature", signature);
        map.put("noncestr", nonceStr);
        map.put("appid", appId);
        map.put("timestamp", timestamp);
        log.info("获取分享签名的url:{},返回的map：{}", url, map);
        return JSONObject.toJSONString(map);
    }
}
